<template>
    <div>
        <el-card>
            <el-input style="width:200px" @clear="searchUser" clearable v-model="searchForm.username" placeholder="请输入用户姓名" class="input-with-select">

            </el-input>
          <el-input style="width:200px" @clear="searchUser" clearable v-model="searchForm.email" placeholder="请输入用户邮箱" class="input-with-select">

          </el-input>
          <el-button icon="Search" @click="searchUser" />
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-upload
                class="upload-demo"
                ref="xls,xlsx"
                :http-request="toUploadExcel"
                :limit="1"
                :multiple="false"
                element-loading-text="正在上传"
                style="margin-top: 9px"
            >
              <el-button size="small">导入用户</el-button>
            </el-upload>
            <el-button size="small" @click="download">下载模板</el-button>
          </div>
            <el-table :data="tableData" border style="width: 100%;margin-top:20px">
                <el-table-column prop="username" label="姓名" width="180" />
                <el-table-column prop="nickname" label="昵称" width="180" />
                <el-table-column prop="phone" label="手机号" width="180" />
                <el-table-column prop="email" label="邮箱" width="240" />
                <el-table-column label="操作" width="330">
                    <template #default="scope">
                      <el-button  type="primary" size="small"
                                  @click="openEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
<!--                        <el-button size="small"-->
<!--                            @click="() => router.push({ path: '/user/detail', query: { id: scope.row.id } })">详情</el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination style="margin-top:20px" :current-page="searchForm.current" :page-size="searchForm.size"
                :page-sizes="[10, 20, 30, 40]" layout="->,total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>
    </div>
  <el-dialog v-model="editFlag" title="用户编辑" width="1000">
    <el-form :model="userForm">
      <el-form-item label="用户昵称" :label-width="200">
        <el-input v-model="userForm.nickname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="头像：" :label-width="200">
        <el-upload
            class="avatar-uploader"
            drag
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            multiple
            :show-file-list="false"
            :http-request="toUploadFile"
        >
          <el-avatar v-if="editFlag && userForm.headIcon" shape="square" :size="'large'" :key="imageKey" :src="userForm.headIcon" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="手机号" :label-width="200">
        <el-input v-model="userForm.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态" :label-width="200">
        <el-select v-model="userForm.status" placeholder="Please select a status">
          <el-option label="开启" :value='1' />
          <el-option label="关闭" :value='0' />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editFlag = false">取消</el-button>
        <el-button @click="updateUser">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import userApi from "../../api/user";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router'
import famousAPI from "../../api/file";

// Dom 挂载之后
onMounted(() => {
    getUserList();
})
const router = useRouter();
let editFlag = ref(false);
let userForm = reactive({
  nickname: '',
  headIcon: '',
  phone: '',
  status:''
});

const imageKey = ref(0);
// 用户数据
let tableData = ref([]);
let total = ref(0);
// 搜索条件
const searchForm = reactive({
    pageNum: 1,
    pageSize: 10,
    username: '',
    email:''
})
// 获取用户列表
const getUserList = async () => {
    const res = await userApi.getUserList(searchForm);
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
}
const handleSizeChange = (size) => {
    searchForm.size = size;
    getUserList();
}
const handleCurrentChange = (current) => {
    searchForm.current = current;
    getUserList();
}
const searchUser = () => {
    searchForm.current = 1;
    getUserList();
}

//下载模板
const download = () => {
  userApi.download();
}
// 删除用户
const deleteUser = (id) => {
    ElMessageBox.confirm(
        '确定要删除该用户信息吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const res = await userApi.delUser({ id: id });
        if (res.data.code === 200) {
            ElMessage.success("删除成功")
            await getUserList();
        } else {
            ElMessage.error("删除失败")
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })
}
const toUploadExcel = (param) => {
  const file = param.file;
  const formData = new FormData();
  formData.append('multipartFile', file);
  userApi.uploadExcel(formData).then(res => {
    if(res.data.code === 200){
      ElMessage.success("上传成功"+ res.data.data)
    }else {
      ElMessage.error(res.data.msg)
    }
  })
  return formData;
}
const openEdit = (row) => {
  userForm = row;
  imageKey.value = row.id;
  editFlag.value = true;
  console.log(userForm);
}

const updateUser = async () => {
  const res = await userApi.updateUser(userForm);
  if (res.data.code === 200) {
    ElMessage.success("修改成功")
    editFlag.value = false
    await getUserList();
  }else{
    ElMessage.error(res.data.msg)
  }
}

const handleHeadIconChange =  (uploadedFile)=>{
  userForm.headIcon = uploadedFile.raw;
  if (userForm.headIcon) {
    const reader = new FileReader();
    reader.onload = function () {
      userForm.headIcon = reader.result;//可以先在本地显示看看
    };
    reader.readAsDataURL(userForm.headIcon);
  }
}

//上传文件
const toUploadFile = async (param) => {
  console.log(param);
  const file = param.file;
  const formData = new FormData();
  formData.append('file', file);
  await famousAPI.add(formData).then((res) => {
    if (res.data.code === 200) {
      ElMessage.success("上传成功")
      let data = res.data.data
      let {fileUrl} = data
      userForm.headIcon = fileUrl ? 'http://localhost:18000/course/famous/preview/' + fileUrl : null
    } else {
      ElMessage.error(res.msg);
    }
  })
}
</script>

<style lang="scss" scoped>

</style>